﻿#include "StructSerialize.h"

StructSerialize::StructSerialize()
{

}

void StructSerialize::test()
{
    XiaomiMobileProduct xiaomi_six;
    xiaomi_six.i = 200;
    xiaomi_six.v.push_back("abc");
    xiaomi_six.v.push_back("bcde");
    xiaomi_six.v.push_back("fghij");
    xiaomi_six.v.push_back("klmnop");

    BYTE *pBuf = new BYTE[64]{0};
    //序列化
    int nBufSize = xiaomi_six.Serialize(pBuf);
    cout<<"buffer size : "<<nBufSize<<endl;

    for(int nOffset = 0; nOffset < 64; nOffset++)
    {
        printf("%02X ",*(pBuf+nOffset));
    }
}

void StructSerialize::printStringSizeof()
{
    cout<<sizeof(string)<<endl;
}
/**
  *@brief MQTT协议Remaining Length（剩余长度）解码
*/
void StructSerialize::Decode(unsigned int tmp[], int nLen)
{
    //这个相当于十进制数，各位位数乘以进制数，然后相加
    unsigned int multiplier = 1;
    unsigned int value = 0;
    int nLoop = 0;
    unsigned int nDigit = 0;
    do
    {
        nDigit = tmp[nLoop],
        value += (nDigit & 127) * multiplier;
        multiplier *= 128;
        nLoop++;
    }
    while ((nDigit & 128) != 0 && nLoop < nLen);

    printf("decode %d\n",value);
}
/**
  *@brief MQTT协议Remaining Length（剩余长度）编码
*/
void StructSerialize::Encode(unsigned int nInput)
{
    unsigned int tmp[] = {0,0,0,0};
    int nLoop = 0;
    do
    {
        unsigned int encodedByte = nInput % 128;
        nInput = nInput / 128;
        if (nInput > 0)
        {
            encodedByte = encodedByte | 128;
        }
        printf("Debug 0x%02X\n",encodedByte);//输出为ff
        tmp[nLoop] = encodedByte;
        nLoop++;
    } while (nInput > 0);

    Decode(tmp,nLoop);
}
